package org.example.gateway.controller;

import org.example.gateway.contants.AdminConstants;
import org.example.gateway.pojo.UserDto;
import org.example.gateway.pojo.vo.CommonResult;
import org.example.gateway.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/regist")
    public CommonResult add(@RequestBody @Validated UserDto dto) {
        userService.add(dto);
        return CommonResult.success();
    }


    @PostMapping("/login")
    public void login(@Validated UserDto dto, HttpServletResponse response) throws IOException {
        userService.login(dto, response);
        response.sendRedirect("/app/list");
    }

    @GetMapping("/login/page")
    public ModelAndView loginPage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login.html");
        return modelAndView;
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie cookie = new Cookie(AdminConstants.TOKEN_NAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "login";
    }
}
